package com.tofu.citcounter;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import java.util.ArrayList;

public class MainActivity extends Activity {
    private static final int MAX_NUMBER_OF_BUILDINGS = 8;
    private static final int ALL_COLORS = 4;
    private static final int BOUNUS_ALL_COLORS = 3;
    private static final int BONUS_ALL_BUILDINGS = 2;
    private static final int BONUS_FIRST = 2;

    private int numberOfSpinners;//current number of buildings
    private ArrayList<Building> buildings;//buildings list from database
    private ArrayList<String> buildingsNames;//used to add spinner
    private Spinner selectedSpinner = null;//used to delete spinner

    private PopupWindow alarmPopup;//alarm popup window

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button addButton = (Button)findViewById(R.id.add_button);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (numberOfSpinners < MAX_NUMBER_OF_BUILDINGS) {
                    addSpinner();
                }
                if (numberOfSpinners == MAX_NUMBER_OF_BUILDINGS) {
                    findViewById(R.id.add_button).setEnabled(false);
                    findViewById(R.id.max_buildings_ch_bx).setVisibility(View.VISIBLE);
                }
            }
        });
        fillBuildingsList();
        setScoresTextValue(0);

        CheckBox maxBuildingsChBx = (CheckBox)findViewById(R.id.max_buildings_ch_bx);
        maxBuildingsChBx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                recalculateScores();
            }
        });
        maxBuildingsChBx.setVisibility(View.INVISIBLE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.option_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.option_delete_all) {
            deleteAllSpinners();
        } else if (item.getItemId() == R.id.option_clear_all) {
            clearAllSpinners();
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        selectedSpinner = (Spinner)v;
        menu.setHeaderTitle(selectedSpinner.getSelectedItem().toString());
        new MenuInflater(this).inflate(R.menu.buildings_actions, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.delete_building) {
            deleteSelectedSpinner();
        }
        return super.onOptionsItemSelected(item);
    }

    public void addSpinner() {
        LinearLayout mainLayout = ((LinearLayout)findViewById(R.id.main_layout));

        Spinner spinner = new Spinner(MainActivity.this);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, buildingsNames);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Building building = buildings.get(i);
                if (building.getColor() > -1) {
                    if (hasBuilding(building, (Spinner)adapterView)) {
                        createAlarmPopUp(R.string.alarm_building_exist);
                        adapterView.setSelection(0);
                    }
                    recalculateScores();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        registerForContextMenu(spinner);
        mainLayout.addView(spinner, mainLayout.getChildCount() - 2);
        numberOfSpinners++;
    }

    private void fillBuildingsNames() {
        if (buildings != null && !buildings.isEmpty()) {
            buildingsNames = new ArrayList<String>();
            for (Building building : buildings) {
                buildingsNames.add(building.getName());
            }
        }

    }

    public void fillBuildingsList() {
        AssetDatabaseOpenHelper dbHelper = new AssetDatabaseOpenHelper(MainActivity.this);
        dbHelper.openDatabase();
        Cursor cursor = dbHelper.selectAll();
        buildings = new ArrayList<Building>();
        if (cursor.moveToFirst()) {
            do {
                buildings.add(new Building(
                        Integer.parseInt(cursor.getString(0)),
                        cursor.getString(1),
                        Integer.parseInt(cursor.getString(2)),
                        Integer.parseInt(cursor.getString(3))
                        ));
            } while (cursor.moveToNext());
        }

        dbHelper.closeDatabase();
        fillBuildingsNames();
    }

    private void setScoresTextValue(int scores) {
        TextView scoresValue = (TextView)findViewById(R.id.scores_value);
        scoresValue.setText(String.valueOf(scores));
    }

    public void recalculateScores() {
        int scores = 0;
        int notEmptyBuildingsNum = 0;
        ArrayList<Integer> colors = new ArrayList<Integer>(4);
        LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main_layout);
        for (int i = 0; i < mainLayout.getChildCount(); i++) {
            View view = mainLayout.getChildAt(i);
            if (view instanceof Spinner) {
                int itemPosition = ((Spinner)view).getSelectedItemPosition();
                Building building = buildings.get(itemPosition);
                if (building.getColor() > -1) {
                    scores += building.getPrice();
                    notEmptyBuildingsNum++;
                    checkNewColor(building.getColor(), colors);
                }
            }
        }
        if (!colors.isEmpty() && colors.size() == ALL_COLORS) {
            scores += BOUNUS_ALL_COLORS;
        }
        if (notEmptyBuildingsNum == MAX_NUMBER_OF_BUILDINGS) {
            scores += BONUS_ALL_BUILDINGS;
            if (((CheckBox)findViewById(R.id.max_buildings_ch_bx)).isChecked()) {
                scores += BONUS_FIRST;
            }
        }
        setScoresTextValue(scores);
    }

    private void checkNewColor(int newColor, ArrayList<Integer> colors) {
        boolean flag = true;
        for (Integer color : colors) {
            if (newColor == color) {
                flag = false;
                break;
            }
        }
        if (flag) {
            colors.add(newColor);
        }
    }

    public boolean hasBuilding(Building newBuilding, Spinner spinner) {
        boolean result = false;
        LinearLayout mainLayout = ((LinearLayout)findViewById(R.id.main_layout));
        for (int i = 0; i < mainLayout.getChildCount(); i++) {
            View view = mainLayout.getChildAt(i);
            if (view instanceof Spinner && !view.equals(spinner)) {
                int itemPosition = ((Spinner)view).getSelectedItemPosition();
                Building building = buildings.get(itemPosition);
                if (building.getId() == newBuilding.getId()) {
                    result = true;
                }
            }
        }
        return result;
    }

    private void createAlarmPopUp(int message) {
        LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.alarm_popup, (ViewGroup) findViewById(R.id.alarm_popup_layout));
        alarmPopup = new PopupWindow(layout, 250, 150, true);
        alarmPopup.setContentView(layout);
        alarmPopup.showAtLocation(layout, Gravity.CENTER, 0, 0);
        ((TextView)layout.findViewById(R.id.popup_message)).setText(message);
        layout.findViewById(R.id.alarm_ok_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alarmPopup.dismiss();
            }
        });
    }

    private void deleteSelectedSpinner() {
        LinearLayout mainLayout = ((LinearLayout)selectedSpinner.getParent());
        mainLayout.removeView(selectedSpinner);
        selectedSpinner = null;
        numberOfSpinners--;
        recalculateScores();
        findViewById(R.id.add_button).setEnabled(true);
        ((CheckBox)findViewById(R.id.max_buildings_ch_bx)).setChecked(false);
        findViewById(R.id.max_buildings_ch_bx).setVisibility(View.INVISIBLE);
    }

    private void deleteAllSpinners() {
        LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main_layout);
        ArrayList<View> toDelete = new ArrayList<View>();
        for (int i = 0; i < mainLayout.getChildCount(); i++) {
            View view = mainLayout.getChildAt(i);
            if (view instanceof Spinner) {
                toDelete.add(view);
            }
        }
        for (View view : toDelete) {
            mainLayout.removeView(view);
        }
        recalculateScores();
    }

    private void clearAllSpinners() {
        LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main_layout);
        for (int i = 0; i < mainLayout.getChildCount(); i++) {
            View view = mainLayout.getChildAt(i);
            if (view instanceof Spinner) {
                ((Spinner)view).setSelection(0);
            }
        }
        ((CheckBox)findViewById(R.id.max_buildings_ch_bx)).setChecked(false);
        recalculateScores();
    }
}
